/**
 * 
 */
package com.jushu.storbox.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderListRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.Order;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.serviceV2.FolderClientV2;

public class LocalFolderService extends AbstractLocalService implements IlocalFolderService {

	private final static String TAG = "LocalFolderService";
	boolean isgetfileSuccess = true;
	@Override
	public void insertFolder(FolderResponse folderResponse,int syncStu) {
		DAOFactory.instance(this.getContext()).getFolderDao().insertFolder(folderResponse,syncStu);

	}

	@Override
	public void updateFolder(FolderResponse folderResponse) {
		DAOFactory.instance(this.getContext()).getFolderDao().updateFolder(folderResponse);
	}

	@Override
	public void updateFolder(FolderInfo folderInfo) {
		DAOFactory.instance(this.getContext()).getFolderDao().updateFolder(folderInfo);
	}

	@Override
	public void insertOrUpdateFolder(FolderResponse folderResponse) {
		// TODO Auto-generated method stub
	}

	@Override
	public List<FolderInfo> getFolderList(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFolderDao().getFolderList(ownerId, folderId);
	}
	
	@Override
	public HashMap<String, FolderInfo> getMappedFolderDatas(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFolderDao().getMappedFolderDatas(ownerId, folderId);
	}
	
	@Override
	public List<FolderInfo> getFolderListPage(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFolderDao().getFolderListPage(ownerId, folderId, Constant.MYCLOUD_GET_FILE_LIST_STATE);
	}

	@Override
	public void deleteFolderAndChild(FileFolderInfo folder) {
		iFileManager mdmTools = FileManagerFactory.getFileManager(this.getContext());
		deleteLocalFolder(mdmTools, folder.getOwnerId(), folder.getId());
	}
	
	@Override
	public void deleteFolderAndChildVirtual(FileFolderInfo folder) {
		deleteLocalFolderMetadata(folder.getOwnerId(), folder.getId());
	}
	
	private void deleteLocalFolder(iFileManager mdmTools, String ownerId, String folderID) {
		DAOFactory.instance(this.getContext()).getFolderDao().deleteFolder(ownerId, folderID);
		List<FileInfo> fileList = DAOFactory.instance(this.getContext()).getFileDao().getFileList(ownerId, folderID);
		for (FileInfo fi : fileList) {
			DAOFactory.instance(this.getContext()).getFileDao().delete(fi);
			mdmTools.deleteFile(fi.getLoctPath());
		}
		List<FolderInfo> folderList = DAOFactory.instance(this.getContext()).getFolderDao().getFolderList(ownerId, folderID);
		for (FolderInfo f : folderList) {
			deleteLocalFolder(mdmTools, f.getOwnerId(), f.getId());
		}
	}
	
	private void deleteLocalFolderMetadata(String ownerId, String folderID) {
		DAOFactory.instance(this.getContext()).getFolderDao().deleteFolder(ownerId, folderID);
		List<FileInfo> fileList = DAOFactory.instance(this.getContext()).getFileDao().getFileList(ownerId, folderID);
		for (FileInfo fi : fileList) {
			DAOFactory.instance(this.getContext()).getFileDao().delete(fi);
		}
		List<FolderInfo> folderList = DAOFactory.instance(this.getContext()).getFolderDao().getFolderList(ownerId, folderID);
		for (FolderInfo f : folderList) {
			deleteLocalFolderMetadata(f.getOwnerId(), f.getId());
		}
	}

	@Override
	public FileFolderInfo renameFolder(FolderResponse folderResponse, FileFolderInfo fileInformation) {
		FileFolderInfo response = null;
		DAOFactory.instance(this.getContext()).getFolderDao().rename(folderResponse, fileInformation);
		response = DAOFactory.instance(this.getContext()).getFolderDao().getFolderById(fileInformation);
		return response;
	}

	@Override
	public void moveFolder(String ownerId, String parentID, String folderID) {
		DAOFactory.instance(this.getContext()).getFolderDao().move(ownerId, parentID, folderID);
	}

	@Override
	public FolderInfo getFolderById(FileFolderInfo fileFolderInfo) {
		return DAOFactory.instance(this.getContext()).getFolderDao().getFolderById(fileFolderInfo);
	}
	
	@Override
	public FolderInfo getFolderById(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFolderDao().getFolderById(ownerId, folderId);
	}
	
	@Override
	public void updateLocalPath(String ownerId, String folderId, String localPath) {
		DAOFactory.instance(this.getContext()).getFolderDao().updateLocalPath(ownerId, folderId, localPath);
	}

	@Override
	public void updateTransStatus(int status, String ownerId, String folderId) {
		DAOFactory.instance(this.getContext()).getFolderDao().updateTransStatus(ownerId, folderId, status);
	}

	@Override
	public int updateSyncStatus(int syncStatus, String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFolderDao().updateSyncStatuc(ownerId, folderId, syncStatus);
	}

	@Override
	public void updateLastRefreshTime(String ownerId, String folderId) {
		long lastRefreshTime = System.currentTimeMillis();
		DAOFactory.instance(this.getContext()).getFolderDao().updateLastRefreshTime(ownerId, folderId, lastRefreshTime);
	}

	@Override
	public long getLastRefreshTime(String ownerId, String folderId) {
		return DAOFactory.instance(this.getContext()).getFolderDao().getLastRefreshTime(ownerId, folderId);
	}
	
	
	@Override
	public void syncFolder(final FileFolderInfo info, final String folderName,final String parentId,final Handler handler,final View itemView) {
		final Context context = this.getContext();
		new Thread(new Runnable() {
			@Override
			public void run() {
				this.syncInnerFolder(info.getOwnerId(), info.getId(), folderName);
			}
			private void syncInnerFolder(String ownerId, String fId, final String fName) {
				ServiceFactory.instance(context).getLocalFolderService().updateSyncStatus(1, ownerId, fId);
				FolderListResponseV2 folderListRespone = null;
				try {
					folderListRespone = syncFolderList(context, ownerId, fId, fName);
				} catch (ClientException e) {
					Message message = handler.obtainMessage(UiConstant.GET_FOLDER_SUB_COLLECTION_FAILED,e);
					message.what = e.getStatusCode();
					message.obj = itemView;
					message.getData().putString("code", e.getCode());
					message.sendToTarget();
				}
				if (null != folderListRespone) {
					List<FolderResponse> folderResponseList = folderListRespone.getFolders();
					for (FolderResponse folderResponse : folderResponseList) {
						syncInnerFolder(folderResponse.getOwnerBy(), folderResponse.getId(), folderName);
					}
				}
			}
		}).start();
	}

	@Override
	public void cancelSyncFolder(final String ownerId, final String folderId, final String folderName) {
		final Context context = this.getContext();
		new Thread(new Runnable() {
			@Override
			public void run() {
				cancelSyncInnerFolder(ownerId, folderId, folderName);
			}

			private void cancelSyncInnerFolder(String ownerId, String fId, final String fName) {
				DAOFactory
				.instance(context)
				.getFileDao()
				.updateSyncStatus(ownerId,
						fId,
						Constant.DOWNLOAD_STATUS_NOCACHE_DB);
				ServiceFactory.instance(context).getLocalFolderService().updateSyncStatus(0, ownerId, fId);
				FolderListResponseV2 folderListRespone = null;
				try {
					folderListRespone = cancelSyncFolderList(context, fId, fName);
				} catch (ClientException e) {
					e.printStackTrace();
				}
				if (null != folderListRespone) {
					List<FolderResponse> folderResponseList = folderListRespone.getFolders();
					// updatelocalityItem(context, folderID, isSysnc);
					for (int i = 0; i < folderResponseList.size(); i++) {
						ServiceFactory.instance(context).getLocalFolderService().updateSyncStatus(1, folderResponseList.get(i).getOwnedBy(),folderResponseList.get(i).getId());
						FolderResponse folderResponse = folderResponseList.get(i);
						cancelSyncInnerFolder(folderResponse.getOwnerBy(),folderResponse.getId(), folderResponse.getName());
					}
				}
			}
		}).start();
	}

	/**
	 * 
	 * @throws ClientException
	 */
	private static FolderListResponseV2 syncFolderList(Context context, String ownerId, String folderID, String fileName)
			throws ClientException {
		FolderListRequestV2 request = new FolderListRequestV2();
		request.setFolderID(folderID);
		request.setLimit(1000);
		request.setOffset(0);
		request.setOwnerID(ownerId);

		Order o = new Order();
		o.setDirection("DESC");
		o.setField("modifiedAt");
		List<Order> olist = new ArrayList<Order>();
		olist.add(o);
		request.setOrder(olist);

		FolderListResponseV2 response = FolderClientV2.getInstance()
				.getFolderInfoList(request, ShareDriveApplication.getInstance().getAuthorization());
		
		List<FileInfo> sqlfileInformationFile = ServiceFactory.instance(context).getLocalFileService()
				.getFileList(ownerId, folderID);
		List<FolderInfo> sqlfileInformationFolder = ServiceFactory.instance(context).getLocalFolderService()
				.getFolderList(ownerId, folderID);
		FileHelper.compareServiceClientFileAndDownload(context, response.getFiles(), sqlfileInformationFile, folderID);
		FileHelper.compareServiceClientFolderAndDownload(context, response.getFolders(), sqlfileInformationFolder);
		return response;
	}

	
	
	/**
	 * 
	 * @throws ClientException
	 * 
	 */
	private static FolderListResponseV2 cancelSyncFolderList(Context context, String folderID, String fileName)
			throws ClientException {
		LogUtil.i(TAG, "start get synce data");		
		FolderListRequestV2 request = new FolderListRequestV2();
		request.setFolderID(folderID);
		request.setLimit(1000);
		request.setOffset(0);
		request.setOwnerID(ShareDriveApplication.getInstance().getWnerID());

		Order o = new Order();
		o.setDirection("DESC");
		o.setField("modifiedAt");
		List<Order> olist = new ArrayList<Order>();
		olist.add(o);
		request.setOrder(olist);

		FolderListResponseV2 response = FolderClientV2.getInstance()
				.getFolderInfoList(request,ShareDriveApplication.getInstance().getAuthorization());
		
		iFileManager mdmTools = FileManagerFactory.getFileManager(context);
		for (FileInfoResponseV2 iterable_element : response.getFiles()) {
			String path = DirectoryUtil.generateFileDownloadPath(context, iterable_element.getOwnerBy(), iterable_element.getId(), iterable_element.getName());
			FileInfo fileInfo = DAOFactory.instance(context).getFileDao().getFile(iterable_element);
			if (fileInfo.isSync()) {
				Log.e("~~", "is sync file");
				DAOFactory.instance(context).getFileDao()
				.updateSyncStatus(iterable_element,Constant.DOWNLOAD_STATUS_NOCACHE_DB);
				DAOFactory.instance(context).getFileDao()
				.updateTransStatus(iterable_element, Constant.DOWNLOAD_NON_UPDATE_DB);

				mdmTools.deleteFile(path);
			}
		}
		return response;
	}

	@Override
	public FileFolderInfo getDatabaseFolderByName(Context context, String ownerId, String folderName) {
		// TODO Auto-generated method stub
		return DAOFactory.instance(this.getContext()).getFolderDao().getFolderByName(ownerId, folderName);
	}
	@Override
	public List<FileFolderInfo> searchInDB(String ownerId, String fileName,Context context){
		List<FileFolderInfo> items = new ArrayList<FileFolderInfo>();
		List<FolderInfo> folderList = DAOFactory.instance(this.getContext()).getFolderDao().getSearchFolderList(ownerId, fileName);
		items.addAll(folderList);
		return items;
	};
}
